package com.kehao.newcoder;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class NC136Solution {

    public int[] solve (int[] xianxu, int[] zhongxu) {
        TreeNode root = buildTree(xianxu,zhongxu,0,xianxu.length-1,0,zhongxu.length-1);
        return rightView(root);
    }

    private int[] rightView(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        dfs(root,list,0);
        int[] result = new int[list.size()];
        for (int i = 0; i < result.length; i++) {
            result[i] = list.get(i);
        }
        return result;
    }

    private void dfs(TreeNode root, List<Integer> list, int i) {
        if(root==null) return;
        if(i>=list.size()){
            list.add(i, root.val);
        }else {
            list.set(i, root.val);
        }
        dfs(root.left,list,i+1);
        dfs(root.right,list,i+1);
    }

    class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
    }

    private TreeNode buildTree(int[] xianxu, int[] zhongxu,int a,int b,int c,int d){
        if(b-a<0){
            return null;
        }
        TreeNode head = new TreeNode();
        head.val = xianxu[a];
        int headPos = 0;
        for(int i=c;i<=d;i++){
            if(head.val==zhongxu[i]){
                headPos = i;
                break;
            }
        }
        head.left = buildTree(xianxu,zhongxu,a+1,a+1+headPos-1-c,c,headPos-1);
        head.right = buildTree(xianxu,zhongxu,b-(d-headPos-1),b,headPos+1,d);
        return head;
    }

    @Test
    public void test01(){
        int[] xianxu = {1,2,4,5,3},zhongxu ={4,2,5,1,3};
        int[] solve = solve(xianxu, zhongxu);
        for (int i : solve) {
            System.out.print(i+" ");
        }
    }
}
